﻿using System;
using System.Web.Mvc;

namespace Presentation.Web.Core.Serialization
{
    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
    public sealed class DeserializeAttribute : CustomModelBinderAttribute {

        public override IModelBinder GetBinder() {
            return new DeserializingModelBinder();
        }

        private sealed class DeserializingModelBinder : IModelBinder {

            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
                if (bindingContext == null) {
                    throw new ArgumentNullException("bindingContext");
                }

                ValueProviderResult vpResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (vpResult == null) {
                    // nothing found
                    return null;
                }

                string serializedValue = (string)vpResult.ConvertTo(typeof(string));
                return DataContractBinarySerializer.DeserializeFromString(bindingContext.ModelType, serializedValue);
            }

        }

    }
}
